from pydantic import BaseModel, Field, validator
from typing import Optional
from config.video_config import VIDEO_CONFIG


class VideoUploadRequest(BaseModel):
    """视频上传请求DTO"""
    video_url: str = Field(..., description="视频文件URL", min_length=1, max_length=2048)
    original_filename: Optional[str] = Field(None, description="原始文件名，为空时自动生成UUID文件名", max_length=255)
    audio_format: Optional[str] = Field("mp3", description="音频输出格式", max_length=10)
    audio_quality: Optional[str] = Field("high", description="音频质量：low/medium/high/lossless", max_length=10)
    
    @validator('video_url')
    def validate_video_url(cls, v):
        """验证视频URL格式"""
        if not v or not v.strip():
            raise ValueError('视频链接不能为空')
        
        # 简单的URL格式验证
        if not (v.startswith('http://') or v.startswith('https://')):
            raise ValueError('视频链接格式不正确，必须以http://或https://开头')
        
        return v.strip()
    
    @validator('audio_format')
    def validate_audio_format(cls, v):
        """验证音频格式"""
        if v and v.lower() not in [fmt.lower() for fmt in VIDEO_CONFIG["supported_audio_formats"]]:
            supported = ', '.join(VIDEO_CONFIG["supported_audio_formats"])
            raise ValueError(f'不支持的音频格式，支持的格式: {supported}')
        
        return v.lower() if v else "mp3"
    
    @validator('audio_quality')
    def validate_audio_quality(cls, v):
        """验证音频质量"""
        if v:
            valid_qualities = ['low', 'medium', 'high', 'lossless']
            if v.lower() not in valid_qualities:
                raise ValueError(f'无效的音频质量，支持的质量: {", ".join(valid_qualities)}')
            return v.lower()
        return "high"  # 默认高质量
    
    @validator('original_filename')
    def validate_original_filename(cls, v):
        """验证原始文件名"""
        if v:
            v = v.strip()
            if not v:
                return None
            
            # 检查文件名长度
            if len(v) > 255:
                raise ValueError('文件名过长，最大支持255个字符')
            
            # 检查是否包含非法字符
            invalid_chars = ['<', '>', ':', '"', '|', '?', '*', '\\', '/']
            for char in invalid_chars:
                if char in v:
                    raise ValueError(f'文件名包含非法字符: {char}')
        
        return v


class TaskCancelRequest(BaseModel):
    """任务取消请求DTO"""
    reason: Optional[str] = Field(None, description="取消原因", max_length=500)


class TaskQueryRequest(BaseModel):
    """任务查询请求DTO"""
    status: Optional[str] = Field(None, description="任务状态筛选")
    limit: Optional[int] = Field(10, description="返回数量限制", ge=1, le=100)
    offset: Optional[int] = Field(0, description="偏移量", ge=0)
    
    @validator('status')
    def validate_status(cls, v):
        """验证任务状态"""
        if v:
            valid_statuses = ['pending', 'processing', 'completed', 'failed', 'cancelled']
            if v.lower() not in valid_statuses:
                raise ValueError(f'无效的任务状态，支持的状态: {", ".join(valid_statuses)}')
            return v.lower()
        return v 